package com.github.binarylei.zkclient.watcher;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.ZkConnection;

import java.util.List;

/**
 * 监听子节点变化
 * @author: leigang
 * @version: 2018-04-06
 */
public class zkClientWatcher {

    private static final String CONNECT_ADDR = "127.0.0.1:2181";
    private static final int SEESION_OUTTIME = 5 * 1000;
    
    public static void main(String[] args) throws InterruptedException {
        ZkClient zkClient = new ZkClient(new ZkConnection(CONNECT_ADDR), SEESION_OUTTIME);
        zkClient.deleteRecursive("/super");

        zkClient.subscribeChildChanges("/super", new IZkChildListener() {
            @Override
            public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
                System.out.println("parentPath：" + parentPath);
                System.out.println("currentChilds：" + currentChilds);
            }
        });

        zkClient.createPersistent("/super");
        Thread.sleep(1000);

        zkClient.createPersistent("/super/c1", "c1");
        Thread.sleep(1000);


        zkClient.createPersistent("/super/c2", "c2");
        Thread.sleep(1000);

        // 修改不会监听
        zkClient.writeData("/super/c2", "c2新内容");
        Thread.sleep(1000);

        zkClient.deleteRecursive("/super");
        Thread.sleep(Integer.MAX_VALUE);
    }

}
